<template>
  <el-container>
    <el-header height="180px">
      <el-form label-width="120px" size="small" label-position="left" style="margin-top:10px">
        <el-form-item label="公告主题：">
          <el-input
            v-model="bulletinTitle"
            size="small"
            clearable
            style="width:400px"
            @keyup.enter.native="handelKeyDown"
            @clear="handleQuery"
          />
        </el-form-item>
        <el-form-item label="发布日期">
          <el-date-picker
            v-model="publishDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width:400px"
            @change="handelDatePicker"
          />
        </el-form-item>
        <el-form-item label="重新发布">
          <el-radio-group v-model="rePublish" size="small" @change="handelRePublishChange">
            <el-radio-button label="全部" />
            <el-radio-button label="是" />
            <el-radio-button label="否" />
          </el-radio-group>
        </el-form-item>
        <el-button v-if="btnAip.add" size="small" type="primary" @click="OnBtnAdd">{{ btnAip.add.buttonCaption }}</el-button>
        <el-button v-if="btnAip.query" size="small" type="primary" @click="handleQuery">{{ btnAip.query.buttonCaption }}</el-button>
        <!-- <el-button type="primary" size="small" @click="OnBtnAdd">新增</el-button> -->
        <!-- <el-button type="primary" size="small" @click="handleQuery">查询</el-button> -->
      </el-form>
    </el-header>
    <el-main :height="mainHeight">
      <el-table
        :data="tableData"
        border
        fit
        size="small"
        empty-text="没有查询到数据"
        highlight-current-row
        :height="mainHeight"
        he
        @sort-change="handelSortChange"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column prop="bulletinTitle" label="公告主题" width="300" sortable />
        <el-table-column prop="bulletinContent" label="公告详情" show-overflow-tooltip />
        <el-table-column prop="publishDate" label="发布日期" sortable width="150" />
        <el-table-column v-if="false" prop="publisher" label="发布人ID" />
        <el-table-column prop="tUsersUserName" label="发布人" width="80" />
        <el-table-column prop="receivers" label="接收租户" show-overflow-tooltip />
        <el-table-column prop="rePublish" label="重新发布" width="80">
          <template slot-scope="scope">{{ scope.row.rePublish == true ? '是':'否' }}</template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150" />
        <el-table-column v-if="false" prop="createId" label="创建人ID" />
        <el-table-column label="操作" fixed="right" width="100px">
          <template slot-scope="scope">
            <el-button v-if="btnAip.edit" size="mini" icon="el-icon-edit" circle @click="handleEdit(scope.$index, scope.row)" />
            <el-button v-if="btnAip.delete" size="mini" type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer>
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :total="totalCount"
        :current-page="pageIndex"
        @current-change="handlePaging"
      />
    </el-footer>
    <el-dialog title="编辑公告信息" :visible.sync="dialogVisible" width="30%">
      <el-form ref="formData" :model="formData" label-width="100px" size="small" :rules="formRules">
        <el-form-item label="系统编号：" prop="id">
          <el-input v-model="formData.id" placeholder="系统生成" readonly />
        </el-form-item>
        <el-form-item label="公告主题：" prop="bulletinTitle">
          <el-input v-model="formData.bulletinTitle" placeholder="请输入公告主题" />
        </el-form-item>
        <el-form-item label="公告内容：" prop="bulletinContent">
          <el-input
            v-model="formData.bulletinContent"
            type="textarea"
            :rows="4"
            :autosize="{ minRows: 3, maxRows: 5}"
            placeholder="请输入公告内容"
          />
        </el-form-item>
        <el-form-item label="发布日期：" prop="publishDate">
          <el-date-picker v-model="formData.publishDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="发布人：" prop="publisher">
          <el-select v-model="formData.publisher" placeholder="请选择">
            <el-option
              v-for="item in publisher"
              :key="item.id"
              :label="item.userName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="重新发布：">
          <el-switch v-model="formData.rePublish" active-text="是" inactive-text="否" />
        </el-form-item>
        <el-form-item label="接收租户：">
          <el-select
            v-model="formData.receivers"
            multiple
            collapse-tags
            clearable
            placeholder="不选表示全部"
          >
            <el-option
              v-for="item in receiver"
              :key="item.id"
              :label="item.tenantShortName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="OnBtnClose">关闭</el-button>
        <el-button type="primary" size="small" @click="OnBtnSaveSubmit">保存</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import RequestObject from '@/utils/requestObject'
import request from '@/utils/request'
import { MessageBox } from 'element-ui'
import DateUtil from '@/utils/dateUtil'
import height from '@/utils/height'
import { getBtnCtr } from '@/utils/BtnControl'
export default {
  data() {
    return {
      btnAip: '',
      headerHeight: '180px',
      footerHeight: '50px',
      mainHeight: '',
      height: 'height:',
      tableData: null,
      bulletinTitle: '',
      publishDate: '',
      rePublish: '全部',
      dialogVisible: false,
      formData: {
        id: 0,
        bulletinTitle: '',
        bulletinContent: '',
        publishDate: new Date(),
        publisher: 0,
        tUsersUserName: '',
        receivers: [],
        rePublish: false,
        createTime: new Date(),
        createId: 0
      },
      publisher: null,
      receiver: null,
      formRules: {
        bulletinTitle: [
          { required: true, message: '请输入公告主题', trigger: 'blur' },
          { min: 5, max: 30, message: '长度需要在5到30个字符', trigger: 'blur' }
        ],
        bulletinContent: [
          { required: true, message: '请输入公告详情', trigger: 'blur' },
          {
            min: 10,
            max: 200,
            message: '详情字符范围在10到200个',
            trigger: 'blur'
          }
        ],
        publishDate: [
          {
            type: 'date',
            required: true,
            message: '请选择发布日期',
            trigger: 'change'
          }
        ],
        publisher: [
          { required: true, message: '请选择发布人', trigger: 'change' }
        ]
      },
      selectedRow: null,
      pageSize: 25,
      totalCount: 0,
      pageIndex: 1,
      sortColumn: '',
      sortOrder: ''
    }
  },
  created() {
    // 动态头部按钮
    this.btnAip = getBtnCtr(
      this.$route.path,
      this.$store.getters.userPermission
    )
    // 初始化表格高度
    this.mainHeight =
      height -
      147 -
      parseInt(this.headerHeight) -
      parseInt(this.footerHeight).toString() +
      'px'
    // 初始化发布人信息
    var publishRequestData = RequestObject.CreateGetObject()
    request({
      url: '/api/tusers',
      method: 'get',
      params: {
        requestObject: JSON.stringify(publishRequestData)
      }
    }).then(res => {
      this.publisher = res.data
    })

    // 初始化接收人信息
    var tenantRequestData = RequestObject.CreateGetObject()
    request({
      url: '/api/ttenants',
      method: 'get',
      params: {
        requestObject: JSON.stringify(tenantRequestData)
      }
    }).then(res => {
      this.receiver = res.data
    })

    // 初始化表格数据
    this.handleQuery()
  },
  methods: {
    handleQuery() {
      var queryConditions = []
      var orderConditions = []
      if (this.bulletinTitle && this.bulletinTitle.length > 0) {
        queryConditions.push({
          column: 'bulletinTitle',
          content: this.bulletinTitle,
          condition: 6
        })
      }
      if (this.publishDate && this.publishDate.length > 0) {
        queryConditions.push({
          column: 'publishDate',
          content:
            DateUtil.Format(this.publishDate[0], 'yyyy-MM-dd') +
            ',' +
            DateUtil.Format(this.publishDate[1], 'yyyy-MM-dd'),
          condition: 10
        })
      }
      console.log(this.rePublish)
      if (this.rePublish != '全部') {
        queryConditions.push({
          column: 'rePublish',
          content: this.rePublish == '是' ? '1' : '0',
          condition: 0
        })
      }
      if (this.sortColumn && this.sortColumn.length > 0) {
        orderConditions.push({
          column: this.sortColumn,
          condition: this.sortOrder
        })
      }
      var queryRequest = RequestObject.CreateGetObject(
        true,
        this.pageSize,
        this.pageIndex,
        queryConditions,
        orderConditions
      )
      request({
        url: '/api/tbulletin',
        method: 'get',
        params: {
          requestObject: JSON.stringify(queryRequest)
        }
      }).then(res => {
        console.log(res.data)
        this.tableData = res.data
        this.totalCount = res.totalNumber
      })
    },
    OnBtnAdd() {
      this.formData.id = 0
      this.formData.bulletinTitle = ''
      this.formData.bulletinContent = ''
      this.formData.publishDate = new Date()
      this.formData.publisher = 0
      this.formData.receivers = []
      this.formData.rePublish = false
      this.formData.createId = 0
      this.dialogVisible = true
    },
    handleEdit(index, selectedRow) {
      this.formData.id = selectedRow.id
      this.formData.bulletinTitle = selectedRow.bulletinTitle
      this.formData.bulletinContent = selectedRow.bulletinContent
      this.formData.publishDate = new Date(selectedRow.publishDate)
      this.formData.publisher = selectedRow.publisher
      this.formData.tUsersUserName = selectedRow.tUsersUserName
      this.formData.receivers = this.GetIntArray(selectedRow.receivers)
      this.formData.rePublish = selectedRow.rePublish
      this.formData.createId = selectedRow.createId
      this.dialogVisible = true
    },
    handleDelete(index, selectedRow) {
      this.$confirm('是否确定并删除该公告信息?', '确认对话框', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        showConfirmButton: true
      }).then(() => {
        var deleteData = RequestObject.CreatePostObject(selectedRow.id)
        request({
          url: '/api/tbulletin/byid',
          method: 'delete',
          data: deleteData
        }).then(res => {
          if (res.code == -1) {
            this.$confirm(res.info, '错误信息', {
              confirmButtonText: '确定',
              type: 'error',
              showCancelButton: false
            })
          } else {
            this.$message({
              message: '删除数据成功',
              type: 'success'
            })
            this.handleQuery() // 查询数据
          }
        })
      })
    },
    OnBtnSaveSubmit() {
      this.$refs.formData.validate(valid => {
        if (!valid) {
          this.$message({
            message: '数据不合法，无法保存',
            type: 'error'
          })
        } else {
          var currData = this.GetPostData()
          console.log(currData)
          var currMethod = 'post'
          if (currData.id !== 0) {
            // 修改
            currMethod = 'put'
          }
          var data = RequestObject.CreatePostObject(currData)
          request({
            url: '/api/tbulletin',
            method: currMethod,
            data: data
          }).then(res => {
            console.log(res)
            if (res.code == -1) {
              this.$confirm(res.info, '错误信息', {
                confirmButtonText: '确定',
                type: 'error',
                showCancelButton: false
              })
            } else {
              this.$message({
                message: '保存数据成功',
                type: 'success'
              })
              this.$refs.formData.resetFields()
              this.dialogVisible = false
              this.handleQuery() // 查询数据
            }
          })
        }
      })
    },
    OnBtnClose() {
      this.dialogVisible = false
      this.$refs.formData.resetFields()
      this.formData.receivers = []
    },
    GetIntArray(str) {
      var result = []
      str.split(',').forEach(function(value, i) {
        result.push(parseInt(value))
      })
      return result
    },
    GetPostData() {
      var result = {
        id: this.formData.id,
        bulletinTitle: this.formData.bulletinTitle,
        bulletinContent: this.formData.bulletinContent,
        publishDate: DateUtil.Format(
          this.formData.publishDate,
          'yyyy-MM-dd HH:mm:ss'
        ),
        publisher: this.formData.publisher,
        tUsersUserName: '',
        receivers: '',
        rePublish: this.formData.rePublish,
        createId: 0
      }
      if (this.formData.receivers && this.formData.receivers.length > 0) {
        result.receivers = this.formData.receivers.join(',')
      } else {
        result.receivers = '0' // 0表示发送给所有租户
      }
      return result
    },
    handlePaging(index) {
      this.pageIndex = index
      this.handleQuery()
    },
    handelRePublishChange() {
      this.handleQuery()
    },
    handelSortChange(currSort) {
      this.sortColumn = currSort.prop
      this.sortOrder = currSort.order == 'ascending' ? 'asc' : 'desc'
      this.handleQuery()
    },
    handelDatePicker() {
      this.handleQuery()
    },
    handelKeyDown() {
      this.handleQuery()
    }
  }
}
</script>
